package org.polaris.org.service.impl;

import org.polaris.basic.service.impl.BaseServiceImpl;
import org.polaris.basic.tool.PageResult;
import org.polaris.org.domain.Department;
import org.polaris.org.mapper.DepartmentMapper;
import org.polaris.org.query.DepartmentQuery;
import org.polaris.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Primary
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional
    public void add(Department department) {
        //处理创建时间
        Date date = new Date();
        department.setCreateTime(date);
        departmentMapper.add(department);
        //处理路径
        String path = "";
        //没有父部门
        if(Objects.isNull(department.getParent()) || Objects.isNull(department.getParent().getId())){
            path = "/"+department.getId();
        }else{
            //有父部门
            Long parentId = department.getParent().getId();
            Department parent = departmentMapper.selectById(parentId);
            path = parent.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //处理创建时间数据
        Date date = new Date();
        department.setUpdateTime(date);
        //处理路径
        String path = "";
        //没有父部门
        if(Objects.isNull(department.getParent()) || Objects.isNull(department.getParent().getId())){
            path = "/"+department.getId();
        }else{
            //有父部门
            Long parentId = department.getParent().getId();
            Department parent = departmentMapper.selectById(parentId);
            path = parent.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void batchDelete(List<Long> ids) {
        if(ids == null || ids.size() == 0){
            throw new RuntimeException("请选择要删除的数据!");
        }
        departmentMapper.batchDelete(ids);
    }

    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.selectDeptTree();
    }
}
